const express = require('express');
const router = express.Router();
const { Op } = require('sequelize');
const db = require('../../models');
const { authenticateToken } = require('../../middleware/auth');
const fs = require('fs').promises;
const path = require('path');

/**
 * 导出日记数据
 * POST /api/export/diaries
 */
router.post('/diaries', authenticateToken, async (req, res) => {
  try {
    const {
      format = 'json',
      startDate,
      endDate,
      categoryIds,
      tagIds
    } = req.body;

    const user_id = req.user.id;

    // 构建查询条件
    const where = { user_id };

    if (startDate && endDate) {
      where.diary_date = {
        [Op.between]: [startDate, endDate]
      };
    } else if (startDate) {
      where.diary_date = {
        [Op.gte]: startDate
      };
    } else if (endDate) {
      where.diary_date = {
        [Op.lte]: endDate
      };
    }

    if (categoryIds && categoryIds.length > 0) {
      where.category_id = {
        [Op.in]: categoryIds
      };
    }

    // 构建包含关系
    const include = [
      {
        model: db.Category,
        as: 'category',
        attributes: ['id', 'name', 'color', 'icon']
      },
      {
        model: db.Tag,
        as: 'tags',
        attributes: ['id', 'name', 'color'],
        through: { attributes: [] }
      },
      {
        model: db.Image,
        as: 'images',
        attributes: ['id', 'filename', 'original_name', 'file_path']
      }
    ];

    // 标签筛选
    if (tagIds && tagIds.length > 0) {
      include.push({
        model: db.Tag,
        as: 'filterTags',
        where: { id: { [Op.in]: tagIds } },
        attributes: [],
        through: { attributes: [] }
      });
    }

    const diaries = await db.Diary.findAll({
      where,
      include,
      order: [['diary_date', 'ASC']]
    });

    const exportData = diaries.map(diary => ({
      id: diary.id,
      title: diary.title,
      content: diary.content,
      diary_date: diary.diary_date,
      weather: diary.weather,
      mood: diary.mood,
      is_public: diary.is_public,
      view_count: diary.view_count,
      created_at: diary.created_at,
      updated_at: diary.updated_at,
      category: diary.category,
      tags: diary.tags,
      images: diary.images
    }));

    // 根据格式生成不同的导出内容
    let exportContent, filename, contentType;

    switch (format) {
      case 'json':
        exportContent = JSON.stringify({
          user: {
            username: req.user.username,
            export_date: new Date().toISOString()
          },
          diaries: exportData
        }, null, 2);
        filename = `diary_export_${Date.now()}.json`;
        contentType = 'application/json';
        break;

      case 'txt':
        exportContent = exportData.map(diary => {
          let content = `标题: ${diary.title}\n`;
          content += `日期: ${diary.diary_date}\n`;
          if (diary.weather) content += `天气: ${diary.weather}\n`;
          if (diary.mood) content += `心情: ${diary.mood}\n`;
          if (diary.category) content += `分类: ${diary.category.name}\n`;
          if (diary.tags.length > 0) {
            content += `标签: ${diary.tags.map(tag => tag.name).join(', ')}\n`;
          }
          content += `\n${diary.content.replace(/<[^>]*>/g, '')}\n`;
          content += `\n${'='.repeat(50)}\n\n`;
          return content;
        }).join('');
        filename = `diary_export_${Date.now()}.txt`;
        contentType = 'text/plain';
        break;

      case 'csv':
        const csvHeaders = ['日期', '标题', '内容', '天气', '心情', '分类', '标签', '浏览次数'];
        const csvRows = exportData.map(diary => [
          diary.diary_date,
          `"${diary.title.replace(/"/g, '""')}"`,
          `"${diary.content.replace(/<[^>]*>/g, '').replace(/"/g, '""')}"`,
          diary.weather || '',
          diary.mood || '',
          diary.category ? diary.category.name : '',
          diary.tags.map(tag => tag.name).join(';'),
          diary.view_count
        ]);
        exportContent = [csvHeaders.join(','), ...csvRows.map(row => row.join(','))].join('\n');
        filename = `diary_export_${Date.now()}.csv`;
        contentType = 'text/csv';
        break;

      default:
        return res.status(400).json({
          error: '不支持的导出格式'
        });
    }

    // 设置响应头
    res.setHeader('Content-Type', contentType);
    res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
    res.setHeader('Content-Length', Buffer.byteLength(exportContent));

    res.send(exportContent);

  } catch (error) {
    console.error('导出日记错误:', error);
    res.status(500).json({
      error: '导出失败'
    });
  }
});

/**
 * 获取导出历史
 * GET /api/export/history
 */
router.get('/history', authenticateToken, async (req, res) => {
  try {
    // 这里可以记录导出历史，目前返回空数组
    res.json({
      success: true,
      data: []
    });
  } catch (error) {
    console.error('获取导出历史错误:', error);
    res.status(500).json({
      error: '获取导出历史失败'
    });
  }
});

module.exports = router; 